var tddjs = tddjs || {};

tddjs.ListController = function (listView, backend) {
    this.view = listView;
    this.backend = backend;
};

tddjs.ListController.prototype = {
    init: function () {
        var self = this;

        this.backend.all(function (err, items) {
            if (err) {
                return self.handleError("Server failed to get todo items", err);
            }

            var todoHTML = "", doneHTML = "", className;

            for (var i = 0, l = items.length; i < l; ++i) {
                if (items[i].done) {
                    doneHTML += "<li class='done'>" + items[i].text + "</li>";
                } else {
                    todoHTML += "<li class='todo'>" + items[i].text + "</li>";
                }
            }

            self.view.innerHTML = todoHTML + doneHTML;
        });
    },

    handleError: function (message, err) {
        var li = document.createElement("li");
        li.className = "error";
        li.innerHTML = message;
        this.view.appendChild(li);
    }
};